<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改会议' : '添加会议'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ flex: '90px' }"
      :wrapper-col="{ flex: '1' }"
    >
      <a-form-item label="会议名称" name="title">
        <a-input
          allow-clear
          :maxlength="20"
          placeholder="请输入会议名称"
          v-model:value="form.title"
        />
      </a-form-item>
      <a-row>
        <a-col :span="12">
          <a-form-item label="会议地址" name="room">
            <a-input
              allow-clear
              placeholder="请输入会议地址"
              v-model:value="form.room"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="坐标地址" name="location">
            <a-input
              allow-clear
              placeholder="请选择地址"
              v-model:value="form.location"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="12">
          <a-form-item label="会议时间" name="meeting_time">
            <a-date-picker
              :show-time="true"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择会议时间"
              v-model:value="form.meeting_time"
            />
            <!-- <a-range-picker
              class="ele-fluid"
              :show-time="true"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model:value="form.meeting_time"
            /> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="签到模式" name="mode">
            <a-radio-group v-model:value="form.mode">
              <a-radio :value="0">报名模式</a-radio>
              <a-radio :value="1">不报名模式</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="12">
          <a-form-item label="报名日期" name="entry_time">
            <a-range-picker
              class="ele-fluid"
              :show-time="true"
              :disabled="form.mode === 1"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model:value="form.entry_time"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="签到日期" name="sign_time">
            <a-range-picker
              class="ele-fluid"
              :show-time="true"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model:value="form.sign_time"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="会议会标" name="image">
        <ele-image-upload
          v-model:value="images"
          :limit="1"
          :before-upload="onBeforeUpload"
          :remove-handler="removeHandler"
          :item-style="{ width: '250px', height: '135px' }"
          :button-style="{ width: '250px', height: '135px' }"
          @upload="onUpload"
        />
      </a-form-item>
      <a-form-item label="会议介绍">
        <tinymce-editor
          ref="editorRef"
          :init="config"
          v-model:value="form.content"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import useFormData from '@/utils/use-form-data';
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  import { Meeting } from '@/api/meeting/model';
  import { addMeeting, updateMeeting } from '@/api/meeting';
  import {
    BeforeUploadType,
    ItemType
  } from 'ele-admin-pro/es/ele-image-upload/types';
  import request from '@/utils/request';

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Meeting | null;
  }>();

  const editorRef = ref<InstanceType<typeof TinymceEditor> | null>(null);
  //
  const formRef = ref<FormInstance | null>(null);
  const images = ref<any>([]);
  const img_obj = reactive<any>({
    url: ''
  });
  // 是否是修改
  const isUpdate = ref(false);
  // 提交状态
  const loading = ref(false);

  const config = ref({
    height: 360,
    // 自定义文件上传(这里使用把选择的文件转成 blob 演示)
    file_picker_callback: (callback: any, _value: any, meta: any) => {
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      // 设定文件可选类型
      if (meta.filetype === 'image') {
        input.setAttribute('accept', 'image/*');
      } else if (meta.filetype === 'media') {
        input.setAttribute('accept', 'video/*');
      }
      input.onchange = () => {
        const file = input.files?.[0];
        if (!file) {
          return;
        }
        if (meta.filetype === 'media') {
          if (!file.type.startsWith('video/')) {
            editorRef.value?.alert({ content: '只能选择视频文件' });
            return;
          }
        }
        if (file.size / 1024 / 1024 > 20) {
          editorRef.value?.alert({ content: '大小不能超过 20MB' });
          return;
        }
        const reader = new FileReader();
        reader.onload = (e) => {
          if (e.target?.result != null) {
            const blob = new Blob([e.target.result], { type: file.type });
            callback(URL.createObjectURL(blob));
          }
        };
        reader.readAsArrayBuffer(file);
      };
      input.click();
    }
  });
  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Meeting>({
    id: undefined,
    title: '',
    room: '',
    mode: 0,
    image: '',
    meeting_time: '',
    entry_time: ['', ''],
    sign_time: ['', ''],
    location: '',
    content: ''
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    title: [
      {
        required: true,
        message: '请输入会议名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    room: [
      {
        required: true,
        message: '请填写会议地址',
        type: 'string',
        trigger: 'blur'
      }
    ],
    meeting_time: [
      {
        required: true,
        message: '请选择会议时间',
        type: 'string',
        trigger: 'blur'
      }
    ],
    sign_time: [
      {
        required: true,
        message: '请选择签到时间',
        type: 'array',
        trigger: 'blur'
      }
    ]
  });

  const onBeforeUpload: BeforeUploadType = (file: File) => {
    // file 即选择后的文件
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return false;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return false;
    }
  };
  const removeHandler = (item) => {
    images.value.forEach((d: any) => {
      if (d.uid === item.uid) {
        images.value = [];
        form.image = '';
        d.deleted = 1;
      }
    });
  };
  const onUpload = (d: ItemType) => {
    const item = images.value.find((t: any) => t.uid === d.uid) ?? d;
    // item 包含的字段参考前面说明
    item.status = 'uploading';
    const formData = new FormData();
    formData.append('file', item.file);
    request({
      url: '/file/upload',
      method: 'post',
      data: formData,
      onUploadProgress: (e: any) => {
        // 文件上传进度回调
        if (e.lengthComputable) {
          item.progress = (e.loaded / e.total) * 100;
        }
      }
    })
      .then((res) => {
        if (res.data.code === 0) {
          item.status = 'done';
          item.url = res.data.data;
          form.image = res.data.data;
        }
      })
      .catch((e: Error) => {
        message.warning(e.message);
        item.status = 'exception';
      });
  };
  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? updateMeeting : addMeeting;
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    images.value = [];
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields(props.data);
          if (props.data.image != null && props.data.image != '') {
            img_obj.url = props.data.image;
            images.value.push(img_obj);
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
